<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票分析工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        button {
            background: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background: #0056b3;
        }
        .window-rule {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
        }
        .window-rule input, .window-rule select {
            flex: 1;
        }
        .add-rule {
            background: #28a745;
        }
        .add-rule:hover {
            background: #218838;
        }
        .remove-rule {
            background: #dc3545;
            padding: 5px 10px;
        }
        .remove-rule:hover {
            background: #c82333;
        }
        .results {
            margin-top: 30px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #dc3545;
            padding: 10px;
            background: #f8d7da;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>股票分析工具</h1>
        
        <form id="filterForm">
            <div class="form-group">
                <label for="startDate">开始日期:</label>
                <input type="date" id="startDate" name="startDate" required>
            </div>

            <div class="form-group">
                <label for="endDate">结束日期:</label>
                <input type="date" id="endDate" name="endDate" required>
            </div>

            <div class="form-group">
                <label for="maxDrawdown">最大回撤百分比:</label>
                <input type="number" id="maxDrawdown" name="maxDrawdown" value="10" step="0.1" min="0" required>
            </div>

            <div class="form-group">
                <label>窗口涨跌幅规则:</label>
                <div id="windowRules">
                    <div class="window-rule">
                        <input type="number" placeholder="窗口天数" name="window" value="5" min="1" required>
                        <input type="number" placeholder="涨跌幅%" name="change" value="-3" step="0.1" required>
                        <select name="type" required>
                            <option value="lt">小于</option>
                            <option value="gt">大于</option>
                            <option value="le">小于等于</option>
                            <option value="ge">大于等于</option>
                        </select>
                        <button type="button" class="remove-rule" onclick="removeRule(this)">删除</button>
                    </div>
                    <div class="window-rule">
                        <input type="number" placeholder="窗口天数" name="window" value="10" min="1" required>
                        <input type="number" placeholder="涨跌幅%" name="change" value="-5" step="0.1" required>
                        <select name="type" required>
                            <option value="lt">小于</option>
                            <option value="gt">大于</option>
                            <option value="le">小于等于</option>
                            <option value="ge">大于等于</option>
                        </select>
                        <button type="button" class="remove-rule" onclick="removeRule(this)">删除</button>
                    </div>
                    <div class="window-rule">
                        <input type="number" placeholder="窗口天数" name="window" value="20" min="1" required>
                        <input type="number" placeholder="涨跌幅%" name="change" value="10" step="0.1" required>
                        <select name="type" required>
                            <option value="gt">大于</option>
                            <option value="lt">小于</option>
                            <option value="ge">大于等于</option>
                            <option value="le">小于等于</option>
                        </select>
                        <button type="button" class="remove-rule" onclick="removeRule(this)">删除</button>
                    </div>
                </div>
                <button type="button" class="add-rule" onclick="addRule()">添加规则</button>
            </div>

            <button type="submit">开始筛选</button>
        </form>

        <div id="results" class="results">
            <div id="loading" class="loading" style="display: none;">正在分析中...</div>
            <div id="error" class="error" style="display: none;"></div>
            <div id="resultContent"></div>
        </div>
    </div>

    <script>
        function addRule() {
            const rulesContainer = document.getElementById('windowRules');
            const newRule = document.createElement('div');
            newRule.className = 'window-rule';
            newRule.innerHTML = `
                <input type="number" placeholder="窗口天数" name="window" min="1" required>
                <input type="number" placeholder="涨跌幅%" name="change" step="0.1" required>
                <select name="type" required>
                    <option value="lt">小于</option>
                    <option value="gt">大于</option>
                    <option value="le">小于等于</option>
                    <option value="ge">大于等于</option>
                </select>
                <button type="button" class="remove-rule" onclick="removeRule(this)">删除</button>
            `;
            rulesContainer.appendChild(newRule);
        }

        function removeRule(button) {
            if (document.querySelectorAll('.window-rule').length > 1) {
                button.parentElement.remove();
            }
        }

        // 设置默认日期
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date();
            const sixtyDaysAgo = new Date();
            sixtyDaysAgo.setDate(today.getDate() - 60);
            
            document.getElementById('startDate').value = sixtyDaysAgo.toISOString().split('T')[0];
            document.getElementById('endDate').value = today.toISOString().split('T')[0];
        });

        document.getElementById('filterForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const resultContent = document.getElementById('resultContent');
            
            loading.style.display = 'block';
            error.style.display = 'none';
            resultContent.innerHTML = '';

            const formData = new FormData(this);
            const windowRules = [];
            
            document.querySelectorAll('.window-rule').forEach(rule => {
                const window = rule.querySelector('input[name="window"]').value;
                const change = rule.querySelector('input[name="change"]').value;
                const type = rule.querySelector('select[name="type"]').value;
                windowRules.push(`${window}:${change}:${type}`);
            });

            const requestData = {
                start_date: formData.get('startDate'),
                end_date: formData.get('endDate'),
                max_drawdown: parseFloat(formData.get('maxDrawdown')),
                windows: windowRules.join(',')
            };

            try {
                const response = await fetch('/api/filter', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.error || '请求失败');
                }

                displayResults(data);
            } catch (err) {
                error.textContent = err.message;
                error.style.display = 'block';
            } finally {
                loading.style.display = 'none';
            }
        });

        function displayResults(data) {
            const resultContent = document.getElementById('resultContent');
            
            if (data.count === 0) {
                resultContent.innerHTML = '<p>没有找到符合条件的股票</p>';
                return;
            }

            let html = `
                <h3>找到 ${data.count} 只符合条件的股票:</h3>
                <table>
                    <thead>
                        <tr>
                            <th>股票代码</th>
                            <th>最大回撤</th>
            `;

            // 添加窗口列
            data.condition.window_changes.forEach(rule => {
                html += `<th>${rule.window}天涨跌幅</th>`;
            });

            html += `
                        </tr>
                    </thead>
                    <tbody>
            `;

            data.results.forEach(stock => {
                html += `
                    <tr>
                        <td>${stock.stock_code}</td>
                        <td>${stock.max_drawdown.toFixed(2)}%</td>
                `;

                // 添加窗口涨跌幅数据
                data.condition.window_changes.forEach(rule => {
                    const windowChange = stock.window_changes.find(wc => wc.window === rule.window);
                    html += `<td>${windowChange ? windowChange.change.toFixed(2) + '%' : 'N/A'}</td>`;
                });

                html += `</tr>`;
            });

            html += `
                    </tbody>
                </table>
            `;

            resultContent.innerHTML = html;
        }
    </script>
</body>
</html>
